# coding=UTF-8
import time
import json
from common.entitys.caiptal import Flow
from service import data_service
from utils import parse_util, cache_util, http_util


# 原地址
# http://push2.eastmoney.com/api/qt/stock/get?ut=fa5fd1943c7b386f172d6893dbfba10b&invt=2&fltt=2&fields=f43,f57,f58,f169,f170,f46,f44,f51,f168,f168,f47,f164,f163,f116,f60,f45,f52,f50,f48,f167,f117,f71,f161,f49,f530,f135,f136,f137,f138,f139,f141,f142,f144,f145,f147,f148,f140,f143,f146,f149,f55,f62,f162,f92,f173,f104,f105,f84,f85,f183,f184,f185,f186,f187,f188,f189,f190,f191,f192,f107,f111,f86,f177,f78,f110,f262,f263,f264,f267,f268,f250,f251,f252,f253,f254,f255,f256,f257,f258,f266,f269,f270,f271,f273,f274,f275,f127,f199,f128,f193,f196,f194,f195,f197,f80,f280,f281,f282,f284,f285,f286,f287,f292&secid=1.603738&cb=jQuery112408230507873719453_1592535705863&_=1592535705891
# 精简地址
# http://push2.eastmoney.com/api/qt/stock/get?ut=fa5fd1943c7b386f172d6893dbfba10b&invt=2&fltt=2&fields=f135,f136,f137,f138,f139,f141,f142,f144,f145,f147,f148,f140,f143,f146,f149&secid=1.603738&cb=jQuery112408230507873719453_1592535705863&_=1592535705891

# f135 ： 主力流入
# f136 ： 主力流出
# f137 ： 主力净流入
# f138 ： 超大单流入
# f139 ： 超大单流出
# f140 ： 超大单净流入
# f141 ： 大单流入
# f142 ： 大单流出
# f143 ： 大单净流入
# f144 ： 中单流入
# f145 ： 中单流出
# f146 ： 中单净流入
# f147 ： 小单流入
# f148 ： 小单流出
# f149 ： 小单净流入
# f168 ： 换手率
# 资金流向
def get_flow(stock_code):
    return flow(stock_code, '', '')


# 资金流向
def flow(stock_code, stock_name, stock_exchange):
    if stock_exchange == '' or stock_name == '':
        stock_name = data_service.stock(stock_code)['name']
        stock_exchange = data_service.stock(stock_code)['exchange']
    # print("获取资金流向,股票编码" + stock_code + ':' + stock_name)
    time_stamp = int(round(time.time() * 1000))
    path_url = 'http://push2.eastmoney.com/api/qt/stock/get?ut=fa5fd1943c7b386f172d6893dbfba10b&invt=2' + \
               '&fltt=2&fields=f135,f136,f137,f138,f139,f141,f142,f144,f145,f147,f148,f140,f143,f146,f149,f168,f116,f116,f117' + \
               '&secid=' + str(stock_exchange) + '.' + str(stock_code) + \
               '&cb=jQuery112408230507873719453_' + str(time_stamp) + '&_=' + str(time_stamp + 28)
    resp_content = str(http_util.request_get(path_url).content.decode('utf-8'))
    resp_date = json.loads(resp_content[resp_content.find('(') + 1:resp_content.rfind(')')]).get('data')
    flow = Flow()
    if not resp_date:
        print("error 获取不到实时资金流")
        return flow
    flow.main_i = parse_util.p_float(resp_date['f135'])
    flow.main_o = parse_util.p_float(resp_date['f136'])
    flow.main_io = parse_util.p_float(resp_date['f137'])
    flow.sb_i = parse_util.p_float(resp_date['f138'])
    flow.sb_o = parse_util.p_float(resp_date['f139'])
    flow.sb_io = parse_util.p_float(resp_date['f140'])
    flow.b_i = parse_util.p_float(resp_date['f141'])
    flow.b_o = parse_util.p_float(resp_date['f142'])
    flow.b_io = parse_util.p_float(resp_date['f143'])
    flow.m_i = parse_util.p_float(resp_date['f144'])
    flow.m_o = parse_util.p_float(resp_date['f145'])
    flow.m_io = parse_util.p_float(resp_date['f146'])
    flow.s_i = parse_util.p_float(resp_date['f147'])
    flow.s_o = parse_util.p_float(resp_date['f148'])
    flow.s_io = parse_util.p_float(resp_date['f149'])
    flow.turnover_rate = parse_util.p_float(resp_date['f168'])
    flow.market_value = parse_util.p_float(resp_date['f116'])
    flow.circulation_value = parse_util.p_float(resp_date['f117'])
    return flow


# 进百条资金流向

# http://push2his.eastmoney.com/api/qt/stock/fflow/daykline/get?cb=jQuery112307151641837778876_1626316625948&lmt=0&klt=101&fields1=f1,f2,f3,f7&fields2=f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61,f62,f63,f64,f65&ut=b2884a393a59ad64002292a3e90d46a5&secid=1.600031&_=1626316625949

# 最近百条资金流向
def flow_hundred(code) -> list:
    url100 = 'http://push2his.eastmoney.com/api/qt/stock/fflow/daykline/get?cb=jQuery112307151641837778876_!!!!!' \
             + '&lmt=0 &klt=101&fields1=f1,f2,f3,f7&fields2=f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61,f62,f63,f64,f65' \
               '&ut=b2884a393a59ad64002292a3e90d46a5&secid=@@@@@.#####&_=$$$$$'
    time_stamp = int(round(time.time() * 1000))
    url100 = url100.replace('!!!!!', str(time_stamp)).replace('@@@@@', str(data_service.stock(code)['exchange']))
    url100 = url100.replace('#####', code).replace('$$$$$', str(time_stamp + 1))
    # resp = requests.get(url100)
    # http_util.request_get(url100)
    resp_content = str(http_util.request_get(url100).content.decode('utf-8'))
    # days_info_str = resp_content.split('(')[1].split(')')[0]
    # days_info_str = resp_content[resp_content.find('(') + 1:resp_content.rfind(')')]
    # resp_json = json.loads(resp_content[resp_content.find('(') + 1:resp_content.rfind(')')])
    # resp_data = json.loads(resp_content[resp_content.find('(') + 1:resp_content.rfind(')')])['data']
    klines = json.loads(resp_content[resp_content.find('(') + 1:resp_content.rfind(')')])['data']['klines']
    klines.reverse()
    top_1000 = []
    for kl in klines:
        top_1000.append(format_flow(kl))
    return top_1000


def format_flow(info):
    # "2021-02-10,258301.0,-140236.0,-118065.0,258301.0,0.0,2.20,-1.20,-1.01,2.20,0.00,5.18,1.77,0.00,0.00",
    il = info.split(',')
    return {'rq': il[0], 'main_io': float(il[1]), 's_io': float(il[2]), 'm_io': float(il[3]), 'b_io': float(il[4]),
            'sb_io': float(il[5]),
            'main_prop': float(il[6]), 's_prop': float(il[7]), 'm_prop': float(il[8]), 'b_prop': float(il[9]),
            'sb_prop': float(il[10]),
            'sp': float(il[11]), 'zf': float(il[12])}


# 机构参与度评测
def flow_jgcyd(code):
    url_jg = 'http://dcfm.eastmoney.com/em_mutisvcexpandinterface/api/js/get?' \
             'type=QGQP_LSJGCYD&token=70f12f2f4f091e459a279469fe49eca5&ps=22&filter=(TRADECODE=!!!!!)&' \
             'st=TRADEDATE&sr=-1&callback=jQuery112309670134575855172_@@@@@&_=#####'
    time_stamp = int(round(time.time() * 1000))
    url_jg = url_jg.replace('!!!!!', code).replace('@@@@@', str(time_stamp)).replace('#####', str(time_stamp + 1))
    # url_jg = url_jg.replace('!!!!!', code)
    # url_jg = url_jg.replace('@@@@@', str(time_stamp))
    # url_jg = url_jg.replace('#####', str(time_stamp + 1))
    # resp = requests.get(url_jg)
    # resp = http_util.request_get(url_jg)
    resp_content = str(http_util.request_get(url_jg).content.decode('utf-8'))
    # days_info_str = resp_content.split('(')[1].split(')')[0]
    # resp_json = json.loads(resp_content.split('(')[1].split(')')[0])
    # {'TRADECODE': '600031', 'STOCKNAME': '三一重工', 'TRADEDATE': '2021-07-14T00:00:00',
    # 'PCTBUYXL': 0.057, 'PCTBUYL': 0.2198, 'ZB': 0.2768,
    # 'ZB3RAVG': 0.35323333333333334, 'ZB50RAVG': 0.34589000000000014,
    # 'JGCYD': 0.313548, 'FLOWINXL': 193405166.0, 'FLOWOUTXL': 758669552.0,
    # 'FLOWINL': 745474304.0, 'FLOWOUTL': 1016781424.0, 'ZLJLR': -836571506.0}
    return json.loads(resp_content[resp_content.find('(') + 1:resp_content.rfind(')')])


# 板块资金流
# url = 'http://push2.eastmoney.com/api/qt/clist/get?cb=jQuery112301436721555740289_1627542516603&pn=1&pz=500&po=1&np=1&fields=f12,f13,f14,f62&fid=f62&fs=m:90+t:3&ut=b2884a393a59ad64002292a3e90d46a5&_=1627542516621'

def board_flow_rt():
    url_bf = 'http://push2.eastmoney.com/api/qt/clist/get?cb=jQuery112301436721555740289_!!!!!&pn=1&pz=500&' \
             'po=1&np=1&fields=f12,f13,f14,f62&fid=f62&fs=m:90+t:3&ut=b2884a393a59ad64002292a3e90d46a5&_=@@@@@'
    time_stamp = int(round(time.time() * 1000))
    url_bf = url_bf.replace('!!!!!', str(time_stamp)).replace('@@@@@', str(time_stamp + 13))
    # resp = requests.get(url_bf)
    # resp_content = str(resp.content.decode('utf-8'))
    # days_info_str = resp_content.split('(')[1].split(')')[0]
    # resp_json = json.loads(days_info_str)
    # return resp_json
    resp_content = str(http_util.request_get(url_bf).content.decode('utf-8'))
    return json.loads(resp_content[resp_content.find('(') + 1:resp_content.rfind(')')])


headers = {'content-type': "application/json; charset=utf8",
           'Authorization': 'APP appid = 4abf1a,token = 9480295ab2e2eddb8'}


# url = 'http://92.push2.eastmoney.com/api/qt/clist/get?cb=jQuery1124046215206471185166_1627543616321&pn=1&pz=20&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&fid=f3&fs=m:90 t:3 f:!50&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f26,f22,f33,f11,f62,f128,f136,f115,f152,f124,f107,f104,f105,f140,f141,f207,f208,f209,f222&_=1627543616322'
#       'http://63.push2.eastmoney.com/api/qt/clist/get?cb=jQuery112403349935111060698_1627544056810&pn=1&pz=20&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&fid=f3&fs=m:90 t:3 f:!50&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f26,f22,f33,f11,f62,f128,f136,f115,f152,f124,f107,f104,f105,f140,f141,f207,f208,f209,f222&_=1627544056811'
#       'http://63.push2.eastmoney.com/api/qt/clist/get?cb=jQuery112403349935111060698_1627544229244&pn=1&pz=20&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&fid=f3&fs=m:90 t:3 f:!50&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f26,f22,f33,f11,f62,f128,f136,f115,f152,f124,f107,f104,f105,f140,f141,f207,f208,f209,f222&_=1627544229257'
#       'http://push2.eastmoney.com/api/qt/clist/get?cb=jQuery1123004336566084372384_1627545440827&fid=f62&po=1&pz=50&pn=1&np=1&fltt=2&invt=2&ut=b2884a393a59ad64002292a3e90d46a5&fs=m:90 t:2&fields=f12,f14,f2,f3,f62,f184,f66,f69,f72,f75,f78,f81,f84,f87,f204,f205,f124,f1,f13'
# 板块资金
def board_flow_info():
    url_bfi = 'http://push2.eastmoney.com/api/qt/clist/get?cb=jQuery1123004336566084372384_!!!!!!&' \
              'fid=f62&po=1&pz=50000&pn=1&np=1&fltt=2&invt=2&ut=b2884a393a59ad64002292a3e90d46a5&fs=m:90 t:2&' \
              'fields=f12,f14,f2,f3,f62,f184,f66,f69,f72,f75,f78,f81,f84,f87,f204,f205,f124,f1,f13'
    time_stamp = int(round(time.time() * 1000))
    url_bfi = url_bfi.replace('!!!!!', str(time_stamp)).replace('@@@@@', str(time_stamp + 13))
    # {'f1': 2, 'f2': 1333.94, 'f3': 2.16, 'f12': 'BK0867', 'f13': 90, 'f14': '富时罗素', 'f62': 19973840896.0,
    #  'f66': 23233523712.0, 'f69': 2.92, 'f72': -3259682816.0, 'f75': -0.41, 'f78': -12911796224.0, 'f81': -1.62,
    #  'f84': -7062044672.0, 'f87': -0.89, 'f124': 1627544404, 'f184': 2.51, 'f204': '比亚迪', 'f205': '002594', 'f206': 0}

    # {'f1': 2, 'f2': 314.18, 'f3': 3.05, 'f12': '603501', 'f13': 1, 'f14': '韦尔股份', 'f62': 316631264.0,
    #  'f66': 224741040.0, 'f69': 6.43, 'f72': 91890224.0, 'f75': 2.63, 'f78': -208689264.0, 'f81': -5.97,
    #  'f84': -107942000.0, 'f87': -3.09, 'f124': 1627545598, 'f184': 9.06, 'f204': '-', 'f205': '-', 'f206': '-'}
    # resp_str = str(requests.get(url_bfi, headers=headers).content.decode('utf-8'))
    resp_str = str(http_util.request_get(url_bfi).content.decode('utf-8'))
    board_list = json.loads((resp_str[resp_str.find('(') + 1:resp_str.rfind(')')])).get('data').get('diff')
    board_dict = {}
    for board_detail in board_list:
        # f13 = board_detail.get('f13')  # 90:板块 1:股票
        if board_detail.get('f13') != 90:
            continue
        board_dict[board_detail.get('f12')] = {
            'rt_price': board_detail.get('f2'),
            'zf': board_detail.get('f3'),
            'board_code': board_detail.get('f12'),
            'main_io': board_detail.get('f62')}

        # board_detail.get('f2')  # 实时价格
        # board_detail.get('f3')  # 涨幅
        # board_detail.get('f12')  # 编码
        # board_detail.get('f13')  # 90:板块 1:股票
        # board_detail.get('f14')  # 名称
        # board_detail.get('f62')  # main_io
        # board_detail.get('f184')  # main_ratio
        # board_detail.get('f66')  # sb_io
        # board_detail.get('f69')  # sb_ratio
        # board_detail.get('f72')  # b_io
        # board_detail.get('f75')  # b_ratio
        # board_detail.get('f78')  # m_io
        # board_detail.get('f81')  # m_ratio
        # board_detail.get('f84')  # s_io
        # board_detail.get('f87')  # s_ratio
        # board_detail.get('f124')  # 时间
        # board_detail.get('f204')  # 流入最大股名称
        # board_detail.get('f205')  # 流入最大股code
        # board_detail.get('f206')  # ???
    return board_dict


# 股票主力资金流
# 数据更新不及时,会出现拉取不到的
# query_list : 需要查询的列表[{}]
# 放入缓存 : 固定3分钟
# return query_list 含有 main_io
def stock_flow_info(query_list):
    url_bfi = 'http://push2.eastmoney.com/api/qt/clist/get?cb=jQuery1123004336566084372384_!!!!!!&' \
              'fid=f62&po=1&pz=50000&pn=1&np=1&fltt=2&invt=2&ut=b2884a393a59ad64002292a3e90d46a5&fs=m:90 t:2&' \
              'fields=f12,f14,f2,f3,f62,f184,f66,f69,f72,f75,f78,f81,f84,f87,f204,f205,f124,f1,f13'
    time_stamp = int(round(time.time() * 1000))
    url_bfi = url_bfi.replace('!!!!!', str(time_stamp)).replace('@@@@@', str(time_stamp + 13))
    # resp_str = str(requests.get(url_bfi, headers=headers).content.decode('utf-8'))
    resp_str = str(http_util.request_get(url_bfi).content.decode('utf-8'))
    board_list = json.loads((resp_str[resp_str.find('(') + 1:resp_str.rfind(')')])).get('data').get('diff')
    stock_dict = {}
    for board_detail in board_list:
        # f13 = board_detail.get('f13')  # 90:板块 1:股票
        if board_detail.get('f13') != 1:
            continue
        stock_dict[board_detail.get('f12')] = {
            'rt_price': board_detail.get('f2'),
            'zf': board_detail.get('f3'),
            'stock_code': board_detail.get('f12'),
            'main_io': board_detail.get('f62')}
    base_key = 'stock_flow_info_cache'
    for i in range(len(query_list)):
        stock = query_list[i]
        code = stock.get('code')
        if code in stock_dict.keys():
            stock['main_io'] = stock_dict.get(code).get('main_io')
        else:
            if cache_util.get_cache_expire(base_key + code) is None:
                flow = get_flow(code)
                cache_util.set_cache_expire(base_key + code, {'stock_code': code, 'main_io': flow.main_io}, 3)
            stock['main_io'] = cache_util.get_cache_expire(base_key + code).get('main_io')
        query_list[i] = stock
    return query_list


# # 资金流 todo whm 整体更新
# 'http://push2.eastmoney.com/api/qt/clist/get?cb=jQuery112300882798110686831_1627545220392&fid=f62&po=1&pz=50&pn=1&np=1&fltt=2&invt=2&ut=b2884a393a59ad64002292a3e90d46a5&fs=m:0+t:6+f:!2,m:0+t:13+f:!2,m:0+t:80+f:!2,m:1+t:2+f:!2,m:1+t:23+f:!2,m:0+t:7+f:!2,m:1+t:3+f:!2&fields=f12,f14,f2,f3,f62,f184,f66,f69,f72,f75,f78,f81,f84,f87,f204,f205,f124,f1,f13'

# 股票资金流
def all_stock_flow_info():
    url_asfi = 'http://push2.eastmoney.com/api/qt/clist/get?cb=jQuery112300882798110686831_!!!!!&fid=f62&po=1&pz=50' \
               '&pn=1&np=1&fltt=2&invt=2&ut=b2884a393a59ad64002292a3e90d46a5&fs=m:0+t:6+f:!2,m:0+t:13+f:!2,m:0+t:80+f:!2,' \
               'm:1+t:2+f:!2,m:1+t:23+f:!2,m:0+t:7+f:!2,m:1+t:3+f:!2&fields=f12,f14,f2,f3,f62,f184,f66,f69,f72,f75,f78,f81,' \
               'f84,f87,f204,f205,f124,f1,f13'
    time_stamp = int(round(time.time() * 1000))
    url_asfi = url_asfi.replace('!!!!!', str(time_stamp))
    # resp = requests.get(url_asfi, headers=headers)
    # resp = http_util.request_get(url_asfi)
    resp_content = str(http_util.request_get(url_asfi).content.decode('utf-8'))
    # days_info_str = resp_content[resp_content.find('(') + 1:resp_content.rfind(')')]
    return json.loads(resp_content[resp_content.find('(') + 1:resp_content.rfind(')')])
    # return resp_json


if __name__ == '__main__':
    print("")
    # {'name': '泰晶科技', 'code': '603738', 'exchange': '1'}
    # aaaa = flow('600678', '', '')
    # aaaa = flow_hundred('600031')
    # aaaa = flow_jgcyd('600031')
    # aaaa = stock_flow_info([])
    aaaa = all_stock_flow_info()
    print(str(aaaa))
    print('aaaa.sb_io')
